package com.czk.bootlettuce.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/12/5 15:00
 */
@RequestMapping("/geo")
@RestController
public class GeospatialController {
    private static final String key = "china:city";
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 初始化地理数据
     */
   // @PostConstruct
    public void GeoInit() {
        redisTemplate.opsForGeo().add(key, new Point(121.47, 31.23), "上海");
        redisTemplate.opsForGeo().add(key, new Point(106.50, 29.53), "重庆");
        redisTemplate.opsForGeo().add(key, new Point(114.05, 22.52), "深圳");
        redisTemplate.opsForGeo().add(key, new Point(116.38, 39.90), "北京");
    }

    /**
     * 获取一个城市的经纬度
     *
     * @param city
     * @return
     */
    @GetMapping("/point/{city}")
    public List getPoint(@PathVariable String city) {
        List position = redisTemplate.opsForGeo().position(key, city);
        return position;
    }

    /**
     * 获取两点距离
     *
     * @param origin
     * @param destination
     * @return
     */
    @GetMapping("/des/{origin}/{destination}")
    public Distance getDistance(@PathVariable String origin, @PathVariable String destination) {
        Distance distance = redisTemplate.opsForGeo().distance(key, origin, destination);
        return distance;
    }

    /**
     * 获取以该经纬度为中心距离内的城市
     *
     * @param jindu
     * @param weidu
     * @param dis
     * @return
     */
    @GetMapping("/radius/{jindu}/{weidu}/{dis}")
    public GeoResults getRadius(@PathVariable double jindu, @PathVariable double weidu, @PathVariable double dis) {
        Circle circle = new Circle(new Point(jindu, weidu), dis);
        GeoResults radius = redisTemplate.opsForGeo().radius(key, circle);
        return radius;
    }
}
